package pvn.com.utils;

import net.rim.device.api.util.MathUtilities;

public class ParseNumbers {
    public static boolean isWhitespace(char a) {
        return "\t ".indexOf(a) >= 0;
    }

    private static long parseLong(String s, int base) {
        int i = 0;
        int sign = 1;
        long r = 0L;

        while ((i < s.length()) && (isWhitespace(s.charAt(i))))
            i++;
        if ((i < s.length()) && (s.charAt(i) == '-')) {
            sign = -1;
            i++;
        } else if ((i < s.length()) && (s.charAt(i) == '+')) {
            i++;
        }
        while (i < s.length()) {
            char ch = s.charAt(i);
            if (('0' <= ch) && (ch < 48 + base))
                r = r * base + ch - 48L;
            else if (('A' <= ch) && (ch < 65 + base - 10))
                r = r * base + ch - 65L + 10L;
            else if (('a' <= ch) && (ch < 97 + base - 10))
                r = r * base + ch - 97L + 10L;
            else
                return r * sign;
            i++;
        }
        return r * sign;
    }

    public static double atof(String s) {
        int i = 0;
        int sign = 1;
        double r = 0.0D;

        double p = 1.0D;
        int state = 0;

        while ((i < s.length()) && (isWhitespace(s.charAt(i)))) {
            i++;
        }
        if ((i < s.length()) && (s.charAt(i) == '-')) {
            sign = -1;
            i++;
        } else if ((i < s.length()) && (s.charAt(i) == '+')) {
            i++;
        }
        while (i < s.length()) {
            char ch = s.charAt(i);
            if (('0' <= ch) && (ch <= '9')) {
                if (state == 0) {
                    r = r * 10.0D + ch - 48.0D;
                } else if (state == 1) {
                    p /= 10.0D;
                    r += p * (ch - '0');
                }
            } else if (ch == '.') {
                if (state == 0)
                    state = 1;
                else
                    return sign * r;
            } else {
                if ((ch == 'e') || (ch == 'E')) {
                    long e = (int) parseLong(s.substring(i + 1), 10);
                    return sign * r * MathUtilities.pow(10.0D, e);
                }
                return sign * r;
            }
            i++;
        }
        return sign * r;
    }
}
